package com.duing.controller;

import com.duing.bean.MapBean;
import com.duing.entity.Graphdata;
import com.duing.entity.IllnessData;
import com.duing.service.DataService;
import com.duing.util.GsonUtil;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

@Controller
public class DataController {

    @Autowired
    private DataService dataService;

    @RequestMapping("/data")
    public String handlerData(String lan, Model model, HttpSession httpSession) {

        List<IllnessData> list = dataService.getList();
        model.addAttribute("dataList", list);

        if(!StringUtils.isEmpty(lan)){
            String[] split = lan.split("_");
            Locale locale = new Locale(split[0],split[1]);
            httpSession.setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale);
        }
        return "dataList";
    }


    @RequestMapping("/")
    @ResponseBody
    public String welcome() {
        return "success";
    }

    @RequestMapping("/graphdata")
    @ResponseBody
    public List<Graphdata> graphdata() {
        return dataService.getGraphDatas();
    }


    @RequestMapping("/thyme")
    public String thyme(Model model) {
        model.addAttribute("name", "Thymeleaf");
        return "index";
    }


    @RequestMapping("/graph")
    public String graph(Model model) {
        Map result = GsonUtil.handleGraphData();
        model.addAttribute("xList", result.get("xList"));
        model.addAttribute("yList", result.get("yList"));
        return "graph";
    }


    @RequestMapping("/map")
    public String map(Model model) {
        List<IllnessData> list = dataService.getList();
        List<MapBean> mapData = new ArrayList<MapBean>();
        List<MapBean> mapData2 = new ArrayList<MapBean>();
        for (IllnessData illnessData : list) {
            MapBean mapBean = new MapBean(illnessData.getArea(),
                    illnessData.getNow_confirm());
            mapData.add(mapBean);

            MapBean mapBean2 = new MapBean(illnessData.getArea(),
                    illnessData.getConfirm());
            mapData2.add(mapBean2);
        }
        model.addAttribute("mapData", new Gson().toJson(mapData));
        model.addAttribute("mapData2", new Gson().toJson(mapData2));
        return "map";
    }
}
